#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <linux/if_ether.h>
#include <linux/in.h>
#include <unistd.h>
#include <time.h>
#define MAX 10000
int shuchu(FILE *file,struct tm *ptm,const char *str){
	int a = fprintf(file,"%d年%d月%d日%d:%d:%d    %s\n",ptm->tm_year+1900,ptm->tm_mon+1,ptm->tm_mday,ptm->tm_hour,ptm->tm_min,ptm->tm_sec,str);
	fflush(file);
	return a;
}
struct tm *shijian(){
	time_t now;
	time(&now);
	return localtime(&now);
}
void jiankong(void){
	int n_read = 0,fd = 0,sum = 0;
	char buffer[4096];
	clock_t start_t, end_t;
	double s;
	FILE *file;
	if((file = fopen("gongji.log","a"))==NULL){
		shuchu(file,shijian(),"打开文件出问题");
		exit(0);
	}
	shuchu(file,shijian(),"程序啓動");
	if((fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0){
		shuchu(file,shijian(),"socket打开错误");
		exit (1);
	}
	while(1)
	{
		n_read = recvfrom(fd, buffer, 4096, 0, NULL, NULL);
		++sum;
		if(sum >= MAX){
			end_t = clock();
			if(((double)(end_t - start_t) / CLOCKS_PER_SEC)<0.10){
				if(shuchu(file,shijian(),"設備被攻擊，已斷開網絡")<0){
					shuchu(file,shijian(),"輸出出現問題");
					fclose(file);
					exit(1);
				}
				if(system("ifconfig eth0 down")==-1){
					shuchu(file,shijian(),"命令出問題");
					fclose(file);
					exit(1);
				}
				sleep(120);
				if(system("ifconfig eth0 up")==-1){
					shuchu(file,shijian(),"命令出問題");
					fclose(file);
					exit(1);
				}
				if(shuchu(file,shijian(),"設備網絡已恢復")<0){
					shuchu(file,shijian(),"輸出出現問題");
					fclose(file);
					exit(1);
				}					                                
			}
			sum = 0;
			start_t = clock();
		}
		//      printf("%d\n",n_read);
		//		printf("%lf\n",(double)(end_t - start_t) / CLOCKS_PER_SEC);

	}

}

int main(int argc, char* argv[])
{
	if(daemon(1,0)==-1){
		exit(1);
	}
	jiankong();
	return 0;

}
